/*
 * @Author: xiaosihan 
 * @Date: 2022-07-11 07:51:56 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2024-04-12 10:10:00
 */
import { Button, InputNumber, message, Modal, Table, Tooltip } from "antd";
import { EditOutlined, CheckOutlined, CloseOutlined } from '@ant-design/icons';
import { autorun } from "mobx";
import { useEffect, useState } from "react";
import homeStore from "./homeStore";
import styles from './index.module.less';
import tinypngApi from "@api/tinypngApi";
import { get } from "lodash";
import { addKeyModel } from "./addKeyModel";
import utils from "@utils";
import { TinypngkeyData } from "@type";
import ApiResponseTest from "@components/ApiResponseTest";

const Home = () => {

    const [page, setPage] = useState(homeStore.page);
    const [pageSize, setPageSize] = useState(homeStore.pageSize);
    const [list, setList] = useState(homeStore.list);
    const [loading, setLoading] = useState(false);
    const [total, setTotal] = useState(homeStore.total);
    const [sumResidue, setSumResidue] = useState(homeStore.sumResidue);
    const [sumCompressionCount, setSumCompressionCount] = useState(homeStore.sumCompressionCount);
    const [editingId, setEditingId] = useState<number | null>(null);
    const [editingResidue, setEditingResidue] = useState<number>(0);
    const [editingCompressionCount, setEditingCompressionCount] = useState<number>(0);


    useEffect(() => autorun(() => {
        setPage(homeStore.page);
        setPageSize(homeStore.pageSize);
        setTotal(homeStore.total);
        setList(homeStore.list);
        setSumResidue(homeStore.sumResidue);
        setSumCompressionCount(homeStore.sumCompressionCount);
    }, { delay: 30 }), []);

    useEffect(() => {

    }, []);

    const columns = [
        {
            key: 'id',
            title: 'id',
            dataIndex: 'id',
            align: 'center'
        }, {
            key: 'ting_png_key',
            title: 'key值',
            dataIndex: 'ting_png_key',
            align: 'center'
        }, {
            key: 'compressionCount',
            title: '本月已用',
            dataIndex: 'compressionCount',
            align: 'center',
            width: 200,
            render: (text: number, record: TinypngkeyData) => {
                if (editingId === record.id) {
                    return (
                        <InputNumber
                            size="small"
                            min={0}
                            max={500}
                            value={editingCompressionCount}
                            onChange={(value) => setEditingCompressionCount(value || 0)}
                            style={{ width: '100px' }}
                        />
                    );
                }
                return text;
            }
        }, {
            key: 'residue',
            title: '本月余额',
            dataIndex: 'residue',
            align: 'center',
            width: 200,
            render: (text: number, record: TinypngkeyData) => {
                if (editingId === record.id) {
                    return (
                        <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                            <InputNumber
                                size="small"
                                min={0}
                                max={500}
                                value={editingResidue}
                                onChange={(value) => setEditingResidue(value || 0)}
                                style={{ width: '100px' }}
                            />
                            <Tooltip title="保存">
                                <Button
                                    type="text"
                                    size="small"
                                    icon={<CheckOutlined />}
                                    onClick={() => handleEditSave(record)}
                                />
                            </Tooltip>
                            <Tooltip title="取消">
                                <Button
                                    type="text"
                                    size="small"
                                    icon={<CloseOutlined />}
                                    onClick={handleEditCancel}
                                />
                            </Tooltip>
                        </div>
                    );
                }
                return (
                    <div style={{ display: 'flex', alignItems: 'center', gap: '8px' }}>
                        {text}
                        <Tooltip title="编辑">
                            <Button
                                type="text"
                                size="small"
                                icon={<EditOutlined />}
                                onClick={() => handleEditStart(record)}
                            />
                        </Tooltip>
                    </div>
                );
            }
        }, {
            key: 'year',
            title: '年',
            dataIndex: 'year',
            align: 'center'
        }, {
            key: 'month',
            title: '月',
            dataIndex: 'month',
            align: 'center'
        }
    ]

    // 获取一个key
    const getKey = async (conut: number) => {
        setLoading(true);
        const result = await tinypngApi.get_key_by_conut(conut);
        const ting_png_key = get(result, ["ting_png_key"]);
        console.log("ting_png_key", ting_png_key);
        homeStore.getList();
        message.open({
            type: 'success',
            content: ting_png_key
        });
        setLoading(false);
    }

    // 添加一个key
    const addKey = async () => {
        setLoading(true);
        const key = await addKeyModel();
        if (key) {
            await homeStore.add(key);
        }
        setLoading(false);
    }

    // 开始编辑余额和已用数量
    const handleEditStart = (record: TinypngkeyData) => {
        setEditingId(record.id);
        setEditingResidue(record.residue);
        setEditingCompressionCount(record.compressionCount);
    }

    // 取消编辑
    const handleEditCancel = () => {
        setEditingId(null);
        setEditingResidue(0);
        setEditingCompressionCount(0);
    }

    // 保存编辑后的余额和已用数量
    const handleEditSave = async (record: TinypngkeyData) => {
        setLoading(true);
        const success = await homeStore.updateResidue(record.ting_png_key, editingCompressionCount, editingResidue);
        if (success) {
            message.success('更新成功');
        } else {
            message.error('更新失败');
        }
        setEditingId(null);
        setEditingResidue(0);
        setEditingCompressionCount(0);
        setLoading(false);
    }

    return (
        <div className={styles.home}>

            <div>
                tinypngkey 共{total}个
                &nbsp;
                <Button
                    loading={loading}
                    size="small"
                    type="primary"
                    onClick={() => getKey(0)}
                >获取一个key</Button>
                &nbsp;
                <Button
                    loading={loading}
                    size="small"
                    type="primary"
                    onClick={() => addKey()}
                >添加一个key</Button>
                &nbsp;
                <Button
                    loading={loading}
                    size="small"
                    type="primary"
                    onClick={async () => {
                        setLoading(true);
                        await homeStore.validate_all_key();
                        setLoading(false);
                    }}
                >校验所有的key</Button>

                <span>{utils.isDev && "开发环境"}</span>

                <span>剩余 : {sumResidue}</span>
                <span>已用 : {sumCompressionCount}</span>
                &nbsp;
                <ApiResponseTest />
            </div>
            <div>
                <a href="https://tinify.cn/developers" target="_blank" >去申请key</a>
            </div>
            <div>使用方法在当前目录执行 (npx xsh-tinypng)</div>

            <Table
                size="small"
                //@ts-ignore
                columns={columns}
                dataSource={list.map(l => ({ ...l, key: l.id }))}
                pagination={{
                    position: ['topLeft'],
                    current: page,
                    pageSize: pageSize,
                    total: total,
                    showTotal: (tatol) => `共计${tatol}个`,
                    onChange(page) {
                        homeStore.getList(page);
                    }
                }}
            />



        </div >
    );
}

export default Home;